/**
 *
 *
 *
 *
 *
 */

package server.modules.oss.controller;

import com.google.gson.Gson;
import server.common.exception.RRException;
import server.common.utils.ConfigConstant;
import server.common.utils.Constant;
import server.common.utils.PageUtils;
import server.common.utils.R;
import server.common.validator.ValidatorUtils;
import server.common.validator.group.AliyunGroup;
import server.common.validator.group.QcloudGroup;
import server.common.validator.group.QiniuGroup;
import server.modules.oss.cloud.CloudStorageConfig;
import server.modules.oss.cloud.OSSFactory;
import server.modules.oss.entity.SysOssEntity;
import server.modules.oss.service.SysOssService;
import server.modules.sys.service.SysConfigService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import server.common.exception.RRException;
import server.common.utils.ConfigConstant;
import server.common.utils.Constant;
import server.common.utils.PageUtils;
import server.common.utils.R;
import server.common.validator.ValidatorUtils;
import server.common.validator.group.AliyunGroup;
import server.common.validator.group.QcloudGroup;
import server.common.validator.group.QiniuGroup;
import server.modules.oss.cloud.CloudStorageConfig;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

/**
 * 文件上传
 *
 * @author
 */
@RestController
@RequestMapping("sys/oss")
public class SysOssController {
	@Autowired
	private SysOssService sysOssService;
    @Autowired
    private SysConfigService sysConfigService;

    private final static String KEY = ConfigConstant.CLOUD_STORAGE_CONFIG_KEY;
	
	/**
	 * 列表
	 */
	@GetMapping("/list")
	// @RequiresPermissions("sys:oss:all")
	public R list(@RequestParam Map<String, Object> params){
		PageUtils page = sysOssService.queryPage(params);

		return R.ok().put("page", page);
	}


    /**
     * 云存储配置信息
     */
    @GetMapping("/config")
    // @RequiresPermissions("sys:oss:all")
    public R config(){
        CloudStorageConfig config = sysConfigService.getConfigObject(KEY, CloudStorageConfig.class);

        return R.ok().put("config", config);
    }


	/**
	 * 保存云存储配置信息
	 */
	@PostMapping("/saveConfig")
	// @RequiresPermissions("sys:oss:all")
	public R saveConfig(@RequestBody CloudStorageConfig config){
		//校验类型
		ValidatorUtils.validateEntity(config);

		if(config.getType() == Constant.CloudService.QINIU.getValue()){
			//校验七牛数据
			ValidatorUtils.validateEntity(config, QiniuGroup.class);
		}else if(config.getType() == Constant.CloudService.ALIYUN.getValue()){
			//校验阿里云数据
			ValidatorUtils.validateEntity(config, AliyunGroup.class);
		}else if(config.getType() == Constant.CloudService.QCLOUD.getValue()){
			//校验腾讯云数据
			ValidatorUtils.validateEntity(config, QcloudGroup.class);
		}

        sysConfigService.updateValueByKey(KEY, new Gson().toJson(config));

		return R.ok();
	}


	/**
	 * 上传文件
	 */
	@PostMapping("/upload")
//	// @RequiresPermissions("sys:oss:all")
	public R upload(@RequestParam("file") MultipartFile file,
					HttpServletRequest request) throws Exception {
		if (file.isEmpty()) {
			throw new RRException("上传文件不能为空");
		}
		System.getProperty("user.dir");
		String uploadPath = System.getProperty("user.dir")+"/../my-vue/static/img/";

		File folder = new File(uploadPath);
		if (!folder.isDirectory()) {
			folder.mkdirs();
		}

		// 对上传的文件重命名，避免文件重名
		String oldName = file.getOriginalFilename();
		String newName = UUID.randomUUID().toString()
				+ oldName.substring(oldName.lastIndexOf("."), oldName.length());

		String filePath ;
		try {
			// 文件保存
			file.transferTo(new File(folder, newName));

			// 返回上传文件的访问路径
//			 filePath = request.getScheme() + "://" + request.getServerName()
//					+ ":" + request.getServerPort()   + newName;

		} catch (IOException e) {
			throw new RRException("上传文件不能为空");
		}

			filePath = "/static/img/"+ newName;
//		//上传文件
//		String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
//		String url = OSSFactory.build().uploadSuffix(file.getBytes(), suffix);

		//保存文件信息
		SysOssEntity ossEntity = new SysOssEntity();
		ossEntity.setUrl(filePath);
		ossEntity.setCreateDate(new Date());
		sysOssService.save(ossEntity);

		return R.ok().put("url", filePath);
	}


	/**
	 * 删除
	 */
	@PostMapping("/delete")
	// @RequiresPermissions("sys:oss:all")
	public R delete(@RequestBody Long[] ids){
		sysOssService.removeByIds(Arrays.asList(ids));

		return R.ok();
	}

}
